package com.dhc.service.controller;

import com.dhc.service.entity.AdminLogin;
import com.dhc.service.entity.dto.AdminLoginDto;
import com.dhc.service.entity.dto.AdminRegisterDto;
import com.dhc.service.entity.vo.AdminLoginVo;
import com.dhc.service.service.AdminLoginService;
import com.dhc.service.utils.jwt.JwtUtils;
import com.dhc.service.utils.result.Result;
import lombok.NonNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

/**
 * @author KAZU
 */
@SuppressWarnings({"all"})
@RestController
@RequestMapping("sys/admin-login")
@CrossOrigin
public class AdminLoginController {

	@Autowired
	private AdminLoginService adminLoginService;

	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

	@PostMapping("login")
	public Result login(@RequestBody @NonNull AdminLoginDto adminLoginDto,
	                    HttpServletRequest request, HttpServletResponse response) {
		AdminLogin adminLogin = adminLoginService.login(adminLoginDto.getUsername(), adminLoginDto.getPassword());
		if (adminLogin == null) {
			LoginException loginException = new LoginException("用户名或密码错误，请检查正确后重试");
			loginException.printStackTrace();
			return Result.error().message(loginException.getMessage());
		} else {
			AdminLoginVo adminLoginVo = new AdminLoginVo();
			String token = JwtUtils.getToken(adminLogin);
			response.setHeader("Authorization", token);
			BeanUtils.copyProperties(adminLogin, adminLoginVo);
			return Result.ok().data("admin", adminLoginVo).data("token", token);
		}
	}
	
	@PostMapping("register")
	public Result register(@RequestBody @NonNull AdminRegisterDto adminRegisterDto) {
		String code = adminRegisterDto.getCode();
		String email = adminRegisterDto.getEmail();
		String codeVerify = redisTemplate.opsForValue().get(email).toString();
		if (codeVerify.isEmpty()) {
			return Result.error().message("验证码已失效，请重新获取");
		}
		if (!code.equals(codeVerify)) {
			return Result.error().message("验证码不正确,请重新输入");
		}
		AdminLogin adminLogin = adminLoginService.register(adminRegisterDto);
		if (adminLogin == null) {
			return Result.error().message("注册失败");
		}
		AdminLoginVo adminLoginVo = new AdminLoginVo();
		BeanUtils.copyProperties(adminLogin, adminLoginVo);
		return Result.ok().data("admin", adminLoginVo);
	}
}
